"""
时间管理模块
功能：计时器，达到指定时间后触发回调
"""
import time


class TimerManager:
    def __init__(self, duration, callback):
        """
        初始化计时器
        :param duration: 持续时间（秒）
        :param callback: 时间到达后的回调函数
        """
        self.duration = duration
        self.callback = callback
        self.start_time = None
        self.is_running = False
        self.check_id = None
        self.root = None
    
    def start(self):
        """开始计时"""
        self.start_time = time.time()
        self.is_running = True
        print(f"计时开始，{self.duration}秒后将触发游戏")
        # 延迟导入避免循环依赖
        from main import DesktopPet
        # 这里需要从外部传入root，简化处理
    
    def check_time(self, root):
        """检查是否到达触发时间"""
        if not self.is_running:
            return
        
        elapsed = time.time() - self.start_time
        
        if elapsed >= self.duration:
            # 时间到达，触发回调
            self.is_running = False
            self.callback()
        else:
            # 继续检查
            self.check_id = root.after(1000, lambda: self.check_time(root))
    
    def reset(self):
        """重置计时器"""
        self.start_time = None
        self.is_running = False
        if self.check_id:
            # 取消之前的检查
            self.check_id = None
    
    def get_remaining_time(self):
        """获取剩余时间（秒）"""
        if not self.is_running or not self.start_time:
            return 0
        elapsed = time.time() - self.start_time
        remaining = max(0, self.duration - elapsed)
        return remaining
